package com.ly.mpayment.rest.recharge.wanheng;

import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.*;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.downshopproduct.IDownShopProductService;
import com.ly.mpayment.persist.service.mobile.IMobileService;
import com.ly.mpayment.persist.service.provincialinformation.IProvincialInformationService;
import com.ly.mpayment.persist.service.user.IUserService;
import com.ly.mpayment.rest.AbsRest;
import com.ly.mpayment.rest.recharge.IpUtil;
import com.ly.mpayment.rest.recharge.RechargeRest;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import java.math.BigDecimal;
import java.util.Date;

@Component
@Path("wanheng")
public class WanHengRest extends AbsRest {
	Logger logger = Logger.getLogger(WanHengRest.class);
	@Autowired
	IDownRechargeFlowService flowService;

	@Autowired
	IUserService userService;

	@Autowired
	IDownShopInfoService shopService;

	@Autowired
	IDownShopProductService productService;

	@Autowired
	IMobileService weiliuService;

	@Autowired
	IProvincialInformationService proService;

	/**
	 * range 必须是1 月包(省内)
	 * @param data
	 * @return
	 */
	@SuppressWarnings("static-access")
	@Path("recharge")
	@POST
	public synchronized String recharge(String data, @Context HttpServletRequest request){
		logger.info("wanheng_recharge:"+data);
		String result = this.validationParameter(data, "token","orderId","mobile","range","alleyway","package","sign");
		if(result == null){
			JSONObject json = JsonUtils.getJSONOBJCT().fromObject(data);
			JSONObject resultJson = JsonUtils.getJSONOBJCT();
			resultJson.put("orderId", json.getString("orderId").trim());
			if(json != null && !json.isEmpty()){
				DownShopInfo info = shopService.findByCallUrl(json.getString("token"));
				if(info == null){
					resultJson.put("resultCode", ResultCode.OTHER.getCode());
					resultJson.put("resultMsg", ResultCode.OTHER.getName());
					return resultJson.toString();
				}
				if(json.containsKey("sign") && json.getString("sign").equals(MD5.md5(getSignRecharge(json,info.getUser().getRemark())))){
					//检查渠道是否正常
					User user = info.getUser();//userService.findOneUser(WanHengUtil.userName[0]);
					//if(user != null && user.getUserstatus() != Config.productStatus[1]){
					//	//对公对私只能跑一种，不能同时跑
					//	//user = userService.findOneUser(WanHengUtil.userName[1]);
					//}

					if(user != null && user.getUserstatus() == Config.productStatus[1]){

						//检查余额
						if(info.getDownshopbalance().compareTo(BigDecimal.ZERO) <= 0 &&
								( info.getCredit().compareTo(BigDecimal.ZERO) <= 0 ||

								(info.getDownshopbalance().compareTo(BigDecimal.ZERO) <= 0

								&& Math.abs(info.getDownshopbalance().intValue()) >= info.getCredit().intValue()))){
								//&& downProduct.getDiscountAmount().compareTo(shop.getCredit()) == 1
							resultJson.put("resultCode", ResultCode.BALANCE.getCode());
							resultJson.put("resultMsg", ResultCode.BALANCE.getName());
							return resultJson.toString();
						}

						if(checkIp(info.getDownshopip(), request)){
							Mobile mobile = checkMobile(json.getString("mobile"));
							if(mobile != null){
								DownShopProduct product = productService.findByIdAndFacevalue(user.getUseruuid(), json.getString("package"));
								if(product != null && product.getStatus() == Config.productStatus[1]){

									//检查充值号段与产品号段是否匹配
									if(mobile != null && !mobile.getProvince().equals(product.getProvincialInformation().getProvincename()) &&  mobile.getState() == Config.mobileState){
										resultJson.put("resultCode", ResultCode.MOBILE.getCode());
										resultJson.put("resultMsg", ResultCode.MOBILE.getName());
										return resultJson.toString();
									}

									//查询渠道对应包体是否配置
									if(json.getString("range").equals(WanHengUtil.range)){
										DownRechargeFlow flow = flowService.findShopUUIDorder(json.getString("orderId").trim(),info.getUser().getUseruuid());
										if(flow == null){
											flow = new DownRechargeFlow();
											Date date = DateUtils.getNowDate();
											flow.setCreatetime(date);
											flow.setDownreqid(json.getString("orderId"));
											flow.setUserFlow(new User(user.getUseruuid()));
											flow.setRechargeamount(product.getPrice());
											flow.setDowonphonenum(json.getString("mobile"));
											flow.setOperators(product.getOperators().getOperatoruid());
											flow.setDownnotificationaddress(WanHengUtil.notifyAddress);
											if(user.getUserstatus() != Config.productStatus[1] || product.getStatus() != Config.productStatus[1]){
												flow.setStatus(Config.status[9] );//缓存订单
											}else{
												flow.setStatus(Config.status[5] );//订单到达
											}
											flow.setBusCode(product.getBusinessType().getBusCode());
											flow.setProvince(mobile.getProvince());
											flow.setCallStatus(Config.callStatus[0]);
											flow.setDownreqnum(1);
											flow.setDownendtimesec(Config.status[3]);
											flow.setDownShopProduct(product);
											flow.setDiscount(product.getDiscount());
											flow.setDiscountAmount(product.getPrice().multiply(product.getDiscount()));
											//查询下游余额
											//检查授信额度 如果有授信额度则可以提交订单，如果没有直接返回约不足，如果授信额度满了，直接返回余额不足
											if(info.getDownshopbalance().compareTo(BigDecimal.ZERO) <= 0 &&
												( info.getCredit().compareTo(BigDecimal.ZERO) <= 0 ||

												(info.getDownshopbalance().compareTo(BigDecimal.ZERO) <= 0

												&& Math.abs(info.getDownshopbalance().intValue()) >= info.getCredit().intValue()))){
												//&& downProduct.getDiscountAmount().compareTo(shop.getCredit()) == 1
												return ResultMessage.getFailt(ResultMessage.shopAmountError);
											}
											//检查余额消耗。如果余额小于0 则取反大于授信 就不能继续提单

											ProvincialInformation provin = this.proService.findByProvincename( mobile.getProvince());
											if (provin != null) {
												flow.setFlowInformation(provin);
											}
											flow = flowService.addDownrechargeflow(flow, info);
												//检查余额 余额不足时 不加入队列处理。
											if(user.getUserstatus() == Config.productStatus[1] && product.getStatus() == Config.productStatus[1]){
												RechargeRest.orderQueue.add(flow);
											}else{
												logger.info("recharge_缓存订单:"+flow.getDowonphonenum());
											}
											resultJson.put("resultCode", ResultCode.SUCCSEE.getCode());
											resultJson.put("resultMsg", ResultCode.SUCCSEE.getName());
											return resultJson.toString();
										}else{
											resultJson.put("resultCode", ResultCode.EXITS.getCode());
											resultJson.put("resultMsg", ResultCode.EXITS.getName());
											return resultJson.toString();
										}
									}else{
										resultJson.put("resultCode", ResultCode.PACKAGE.getCode());
										resultJson.put("resultMsg", ResultCode.PACKAGE.getName());
										return resultJson.toString();
									}
								}else{
									resultJson.put("resultCode", ResultCode.PACKAGE.getCode());
									resultJson.put("resultMsg", ResultCode.PACKAGE.getName());
									return resultJson.toString();
								}
							}else{
								resultJson.put("resultCode", ResultCode.MOBILE.getCode());
								resultJson.put("resultMsg", ResultCode.MOBILE.getName());
								return resultJson.toString();
							}
						}else{
							resultJson.put("resultCode", ResultCode.IP.getCode());
							resultJson.put("resultMsg", ResultCode.IP.getName());
							return resultJson.toString();
						}
					}else{
						resultJson.put("resultCode", ResultCode.CHANNEL.getCode());
						resultJson.put("resultMsg", ResultCode.CHANNEL.getName());
						return resultJson.toString();
					}
				}else{
					resultJson.put("resultCode", ResultCode.SIGN.getCode());
					resultJson.put("resultMsg", ResultCode.SIGN.getName());
					return resultJson.toString();
				}
			}else{
				resultJson.put("resultCode", ResultCode.OTHER.getCode());
				resultJson.put("resultMsg", ResultCode.OTHER.getName());
				return resultJson.toString();
			}
		}
		return result;
	}
	/**
	 * 100：充值失败，
		200: 充值成功，
		202：订单充值中
		203：订单未存在
	 * token=value&orderId=value1&key=密钥
	 * @param data
	 * @param request
	 * @return
	 */
	@SuppressWarnings("static-access")
	@Path("searchOrder")
	@POST
	public String searchOrder(String data, @Context HttpServletRequest request){
		logger.info("wanheng_recharge:"+data);
		String result = this.validationParameter(data, "token","orderId","sign");
		if(result == null){
			JSONObject json = JsonUtils.getJSONOBJCT().fromObject(data);
			JSONObject resultJson = JsonUtils.getJSONOBJCT();
			resultJson.put("orderId", json.getString("orderId").trim());
			if(json != null && !json.isEmpty()){
				DownShopInfo info = shopService.findByCallUrl(json.getString("token"));
				if(info == null){
					resultJson.put("resultCode", ResultCode.TOKEN.getCode());
					resultJson.put("resultMsg", ResultCode.TOKEN.getName());
					return resultJson.toString();
				}

				if(json.containsKey("sign") && json.getString("sign").equals(MD5.md5(getSignSearch(json,info.getUser().getRemark())))){

					//检查渠道是否正常
					DownRechargeFlow flow = flowService.findShopUUIDorder(json.getString("orderId").trim(),info.getUser().getUseruuid());
					if(flow == null){
						resultJson.put("resultCode", ResultCode.ORDER_NOT_EXITS.getCode());
						resultJson.put("resultMsg", ResultCode.ORDER_NOT_EXITS.getName());
						return resultJson.toString();
					}else{

						if(checkIp(info.getDownshopip(), request)){
//							orderId=value1&resultCode=value2&mobile=value3&package=value4&key=密钥
							if(flow.getStatus() == Config.status[0]){
								resultJson.put("resultCode", ResultCode.RECHARGEING.getCode());
								resultJson.put("resultMsg", ResultCode.RECHARGEING.getName());
								return resultJson.toString();
							}else if(flow.getStatus() == Config.status[2]){
								resultJson.put("resultCode", ResultCode.FAILT.getCode());
								resultJson.put("resultMsg", ResultCode.FAILT.getName());
								return resultJson.toString();
							}else if(flow.getStatus() == Config.status[1]){
								resultJson.put("resultCode", ResultCode.RECHARGE_SUCCESS.getCode());
								resultJson.put("resultMsg", ResultCode.RECHARGE_SUCCESS.getName());
								resultJson.put("mobile", flow.getDowonphonenum());
								resultJson.put("package", flow.getDownShopProduct().getDownfacevalue());
								StringBuilder sb = new StringBuilder();
//								orderId=value1&resultCode=value2&mobile=value3&package=value4&key=密钥
								sb.append("orderId=");
								sb.append(flow.getDownreqid());
								sb.append("&resultCode=");
								sb.append(ResultCode.RECHARGE_SUCCESS.getCode());
								sb.append("&mobile=");
								sb.append( flow.getDowonphonenum());
								sb.append("&package=");
								sb.append(flow.getDownShopProduct().getDownfacevalue());
								sb.append("&key=");
								sb.append(info.getUser().getRemark());
								resultJson.put("sign",MD5.md5(sb.toString()));
								logger.info("wanheng_sing:"+resultJson.toString());
								return resultJson.toString();
							}
						}else{
							resultJson.put("resultCode", ResultCode.IP.getCode());
							resultJson.put("resultMsg", ResultCode.IP.getName());
							return resultJson.toString();
						}
					}

				}else{
					resultJson.put("resultCode", ResultCode.SIGN.getCode());
					resultJson.put("resultMsg", ResultCode.SIGN.getName());
					return resultJson.toString();
				}
			}else{
				resultJson.put("resultCode", ResultCode.OTHER.getCode());
				resultJson.put("resultMsg", ResultCode.OTHER.getName());
				return resultJson.toString();
			}
		}
		return result;
	}


	private Mobile checkMobile(String phoneNum){
		String province = "";
		//匹配号码与运营商不符的直接返回错误
		Mobile mobile = weiliuService.findPhone(phoneNum.substring(0, 7));
		if (mobile == null) {
			// 查询聚合数据
			JSONObject city = HttpClient.httpGetJuhe(phoneNum);
			if (city.containsKey("resultcode") && city.getString("resultcode").equals("200")
					&& city.containsKey("result") && !city.getJSONObject("result").isNullObject()) {
				if (city != null && city.getJSONObject("result") != null) {
					// 更新新的电话号段到本地数据库中
					try {
						mobile = new Mobile();
						mobile.setCityCode(city.getJSONObject("result").getString("areacode"));
						mobile.setPhone(phoneNum.substring(0, 7));
						mobile.setProvince(city.getJSONObject("result").getString("province"));
						mobile.setCity(city.getJSONObject("result").getString("city"));
						mobile.setPostCode(city.getJSONObject("result").getString("zip"));
						mobile.setServiceProvider("中国" + city.getJSONObject("result").getString("company"));
						this.weiliuService.saveMobile(mobile);
						return mobile;
					}catch (Exception e){
						e.printStackTrace();
						logger.info("异常号码:"+phoneNum);
					}
					return null;
				} else {
					return null;
				}
			}
		}
		return mobile;
	}

	private boolean checkIp(String customerIp, HttpServletRequest request) {
		boolean tempIp = false;
		String ips[] = customerIp.trim().split(",");
		for (String ip : ips) {
			if (ip.equals(IpUtil.getIp(request))) {
				tempIp = true;
				break;
			}
		}
		if (!tempIp) {
			logger.info("checkIp:" + IpUtil.getIp(request));
		}
		return tempIp;
	}
	/**
	 * 	//检查签名 token=value&orderId=value1&mobile=value2&range=value3&package=value4&key=密钥
	 * @param json
	 * @return
	 */
	private String getSignRecharge(JSONObject json,String key){
		StringBuilder sb = new StringBuilder();
		sb.append("token=");
		sb.append(json.getString("token"));
		sb.append("&orderId=");
		sb.append(json.getString("orderId"));
		sb.append("&mobile=");
		sb.append(json.getString("mobile"));
		sb.append("&range=");
		sb.append(json.getString("range"));
		sb.append("&package=");
		sb.append(json.getString("package"));
		sb.append("&key=");
		sb.append(key);
		return sb.toString();
	}

	/**
	 * token=value&orderId=value1&key=密钥
	 * @param json
	 * @return
	 */
	private String getSignSearch(JSONObject json,String key){
		StringBuilder sb = new StringBuilder();
		sb.append("token=");
		sb.append(json.getString("token"));
		sb.append("&orderId=");
		sb.append(json.getString("orderId"));
		sb.append("&key=");
		sb.append(key);
		return sb.toString();
	}
}
